package utils

import (
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
)

func MD5(str string) string {
	ctx := md5.New()
	ctx.Write([]byte(str))
	return hex.EncodeToString(ctx.Sum(nil))
}

func Sha1(str string) string {
	t := sha1.New()
	_, _ = io.WriteString(t, str)
	return fmt.Sprintf("%x", t.Sum(nil))
}

//json字符串转slice
func StringToSliceString(content string) (result []string) {
	if content == "" {
		return
	}
	_ = json.Unmarshal([]byte(content), &result)
	return
}

//slice字符串转json
func SliceStringToString(content []string) (result string) {
	jsonStr, err := json.Marshal(content)
	if err == nil {
		result = string(jsonStr)
	}
	return
}

// 提取全部数字
func ExtractNumChar(content string) (result string) {
	if content == "" {
		return
	}
	strSlice := []int32(content)
	for i := 0; i < len(strSlice); i++ {
		if strSlice[i] >= 48 && strSlice[i] <= 57 {
			result += string(strSlice[i])
		}
	}
	return
}

// 提取全部英文字符
func ExtractEnChar(content string) (result string) {
	if content == "" {
		return
	}
	strSlice := []int32(content)
	for i := 0; i < len(strSlice); i++ {
		if (strSlice[i] >= 65 && strSlice[i] <= 90) || (strSlice[i] >= 97 && strSlice[i] <= 122) {
			result += string(strSlice[i])
		}
	}
	return
}

// 提取全部中文字符
func ExtractCnChar(content string) (result string) {
	if content == "" {
		return
	}
	strSlice := []int32(content)
	for i := 0; i < len(strSlice); i++ {
		if strSlice[i] >= 19968 && strSlice[i] <= 40869 {
			result += string(strSlice[i])
		}
	}
	return
}

// 提取全部英文数字中文字符
func ExtractNumEnCnChar(content string) (result string) {
	if content == "" {
		return
	}
	strSlice := []int32(content)
	for i := 0; i < len(strSlice); i++ {
		if (strSlice[i] >= 48 && strSlice[i] <= 57) ||
			(strSlice[i] >= 65 && strSlice[i] <= 90) ||
			(strSlice[i] >= 97 && strSlice[i] <= 122) ||
			(strSlice[i] >= 19968 && strSlice[i] <= 40869) {
			result += string(strSlice[i])
		}
	}
	return
}

// 提取姓名
func ExtractNameChar(content string) (result string) {
	if content == "" {
		return
	}
	strSlice := []int32(content)
	//英文名包括点大、空格、横线
	for i := 0; i < len(strSlice); i++ {
		if strSlice[i] == 32 || //空格
			strSlice[i] == 183 || //点
			strSlice[i] == 45 || //-
			(strSlice[i] >= 65 && strSlice[i] <= 90) ||
			(strSlice[i] >= 97 && strSlice[i] <= 122) ||
			(strSlice[i] >= 19968 && strSlice[i] <= 40869) {
			result += string(strSlice[i])
		}
	}
	return
}

// Utf8StrCut 中文字符切取
func Utf8StrCut(content string, length int) string {
	if len(content) == 0 {
		return content
	}
	utf8Str := []rune(content)
	count := len(utf8Str)
	if count < length {
		length = count
	}
	return string(utf8Str[0:length])
}
